package org.dromara.bean.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.datatype.jsr310.DecimalUtils;
import org.dromara.bean.config.CarriageConfig;
import org.dromara.bean.config.WxPaymentConfig;
import org.dromara.bean.constant.BusinessCodeTypeConstant;
import org.dromara.bean.constant.CommonCode;
import org.dromara.bean.constant.OrderStatusConstant;
import org.dromara.bean.constant.OrderTypeConstant;
import org.dromara.bean.controller.PaymentController;
import org.dromara.bean.domain.*;
import org.dromara.bean.domain.bo.HisGoodsDetailsBo;
import org.dromara.bean.domain.pay.OrderModel;
import org.dromara.bean.domain.vo.*;
import org.dromara.bean.mapper.*;
import org.dromara.bean.service.IBaseMemberAddressService;
import org.dromara.bean.service.IBaseMemberRefundService;
import org.dromara.bean.util.BusinessCodeUtil;
import org.dromara.bean.util.wxApi.WXHandleUtil;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.ReturnOrderModel;
import org.dromara.common.core.domain.model.WxRefundResponseDTO;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.DictService;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.bean.domain.bo.HisGoodsOrderBo;
import org.dromara.bean.service.IHisGoodsOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 商城订单Service业务层处理
 *
 * @author Lion Li
 * @date 2024-12-23
 */
@RequiredArgsConstructor
@Service
public class HisGoodsOrderServiceImpl implements IHisGoodsOrderService {

    private final HisGoodsOrderMapper baseMapper;

    private final HisGoodsMapper goodsMapper;

    private final BusinessCodeUtil businessCodeUtil;

    private final HisGoodsDetailsMapper detailsMapper;


    private final DictService iBaseDictService;

    private final HisMemberMapper memberMapper;

    @Autowired
    PaymentController paymentController;


    private final IBaseMemberRefundService memberRefundService;


    private final WXHandleUtil wxHandleUtil;

    private final IBaseMemberAddressService memberAddressService;

    private final HisGoodsCarMapper hisGoodsCarMapper;

    /**
     * 查询商城订单
     *
     * @param id 主键
     * @return 商城订单
     */
    @Override
    public HisGoodsOrderVo queryById(Long id) {
        HisGoodsOrderVo hisGoodsOrderVo = baseMapper.orderInfo(id);
        // 根据当前订单的 ID 查询对应的 HisGoodsDetails 记录列表
        List<HisGoodsDetailsVo> hisGoodsDetails = detailsMapper.selectVoList(
            Wrappers.lambdaQuery(HisGoodsDetails.class)
                .eq(HisGoodsDetails::getOrderId, hisGoodsOrderVo.getId())
        );

        // 遍历 HisGoodsDetails 记录列表
        hisGoodsDetails.forEach(item -> {
            // 根据商品 ID 查询对应的商品信息，并设置到 HisGoodsDetailsVo 对象中
            HisGoodsVo hisGoodsVo = goodsMapper.selectVoById(item.getGoodsId());
            item.setGoods(BeanUtil.copyProperties(hisGoodsVo, HisExcelGoodsVo.class));
        });

        // 将查询到的 HisGoodsDetails 记录列表设置到当前订单对象中
        hisGoodsOrderVo.setGoodsOrderDetails(hisGoodsDetails);

        hisGoodsOrderVo.setAddress(memberAddressService.getById(hisGoodsOrderVo.getAddressId()));

        return hisGoodsOrderVo;
    }

    /**
     * 分页查询商城订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商城订单分页列表
     */
    @Override
    public TableDataInfo<HisGoodsOrderVo> queryPageList(HisGoodsOrderBo bo, PageQuery pageQuery) {
        Map<String, Object> params = bo.getParams();
        Page<HisGoodsOrderVo> result = baseMapper.orderList(pageQuery.build(), bo, params);
        // 遍历查询结果中的每一条记录
        result.getRecords().forEach(obj -> {
            // 根据当前订单的 ID 查询对应的 HisGoodsDetails 记录列表
            List<HisGoodsDetailsVo> hisGoodsDetails = detailsMapper.selectVoList(
                Wrappers.lambdaQuery(HisGoodsDetails.class)
                    .eq(HisGoodsDetails::getOrderId, obj.getId())
            );

            // 遍历 HisGoodsDetails 记录列表
            hisGoodsDetails.forEach(item -> {
                // 根据商品 ID 查询对应的商品信息，并设置到 HisGoodsDetailsVo 对象中
                HisGoodsVo hisGoodsVo = goodsMapper.selectVoById(item.getGoodsId());
                item.setGoods(BeanUtil.copyProperties(hisGoodsVo, HisExcelGoodsVo.class));
            });

            // 将查询到的 HisGoodsDetails 记录列表设置到当前订单对象中
            obj.setGoodsOrderDetails(hisGoodsDetails);
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的商城订单列表
     *
     * @param bo 查询条件
     * @return 商城订单列表
     */
    @Override
    public List<HisGoodsOrderVo> queryList(HisGoodsOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        List<HisGoodsOrderVo> result = baseMapper.orderList(bo, params);
        // 遍历查询结果中的每一条记录
        result.forEach(obj -> {
            // 根据当前订单的 ID 查询对应的 HisGoodsDetails 记录列表
            List<HisGoodsDetailsVo> hisGoodsDetails = detailsMapper.selectVoList(
                Wrappers.lambdaQuery(HisGoodsDetails.class)
                    .eq(HisGoodsDetails::getOrderId, obj.getId())
            );
            // 遍历 HisGoodsDetails 记录列表
            hisGoodsDetails.forEach(item -> {
                // 根据商品 ID 查询对应的商品信息，并设置到 HisGoodsDetailsVo 对象中
                HisGoodsVo hisGoodsVo = goodsMapper.selectVoById(item.getGoodsId());
                item.setGoods(BeanUtil.copyProperties(hisGoodsVo, HisExcelGoodsVo.class));
            });

            // 将查询到的 HisGoodsDetails 记录列表设置到当前订单对象中
            obj.setGoodsOrderDetails(hisGoodsDetails);
        });
        return result;
    }

    private LambdaQueryWrapper<HisGoodsOrder> buildQueryWrapper(HisGoodsOrderBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HisGoodsOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getMemberId() != null, HisGoodsOrder::getMemberId, bo.getMemberId());
        lqw.eq(StringUtils.isNotBlank(bo.getLogisticsNo()), HisGoodsOrder::getLogisticsNo, bo.getLogisticsNo());
        lqw.eq(bo.getLogisticsCompanyId() != null, HisGoodsOrder::getLogisticsCompanyId, bo.getLogisticsCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNumber()), HisGoodsOrder::getOrderNumber, bo.getOrderNumber());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getStatus()), HisGoodsOrder::getStatus, bo.getStatus());
        lqw.eq(HisGoodsOrder::getDelFlag, 0);
        return lqw;
    }

    /**
     * 新增商城订单
     *
     * @param bo 商城订单
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HisGoodsOrder insertByBo(List<HisGoodsOrderBo> bo) {

        LoginUser loginUser = LoginHelper.getLoginUser();
        // 订单对象
        HisGoodsOrder order = new HisGoodsOrder();
        // 订单详情对象
        List<HisGoodsDetails> hisGoodsDetails = new ArrayList<>();

        // 设置会员归属
        order.setMemberId(loginUser.getUserId());
        if (ObjectUtil.isNotEmpty(bo)) {
            order.setAddressId(bo.get(0).getAddressId());
        }
        BigDecimal totalPrice = new BigDecimal(0);

        List<Long> carIds = new ArrayList<>();
        // TODO 不允许使用前端任何关系到金额的数据
        for (HisGoodsOrderBo goodsOrderBo : bo) {
            HisGoodsDetails details = new HisGoodsDetails();
            HisGoods hisGoods = goodsMapper.selectById(goodsOrderBo.getId());
            // 总金额等于当前金额加上商品数量乘以金额
            BigDecimal multiply = hisGoods.getPrice().multiply(new BigDecimal(goodsOrderBo.getCount()));

            totalPrice = totalPrice.add(multiply);

            // 详情
            details.setMemberId(loginUser.getUserId());
            details.setGoodsId(goodsOrderBo.getId());
            details.setTotalPrice(multiply);
            details.setCount(goodsOrderBo.getCount());
            hisGoodsDetails.add(details);
            if (ObjectUtil.isNotEmpty(goodsOrderBo.getCarId())) {
                carIds.add(goodsOrderBo.getCarId());
            }
        }


        String number = businessCodeUtil.genCode(BusinessCodeTypeConstant.HIS_COMMODITY_EXAMINE);
        order.setOrderNumber(number);
        // 如果总金额是0直接待发货
        if (totalPrice.compareTo(BigDecimal.ZERO) <= 0) {
            order.setStatus((OrderStatusConstant.SHOP_PAID));
        } else {
            order.setStatus(OrderStatusConstant.SHOP_FOR_PAY);
        }

        // 获取运费规则
        CarriageConfig carriage = iBaseDictService.getDictToObj("carriage", new CarriageConfig());
        if (bo.get(0).getZt() != 1) {
            // 判断总金额是否大于full 如果小于则总金额再加上carriage运费金额
            if (totalPrice.compareTo(new BigDecimal(carriage.getFull())) < 0) {
                order.setCarriage(new BigDecimal(carriage.getCarriage()));
                totalPrice = totalPrice.add(new BigDecimal(carriage.getCarriage()));
            }
        } else {
            order.setZt(1);
        }


        order.setTotalPrice(totalPrice);
        baseMapper.insert(order);
        hisGoodsDetails.forEach(obj -> {
            obj.setOrderId(order.getId());
        });
        detailsMapper.insertBatch(hisGoodsDetails);

        if (ObjectUtil.isNotEmpty(carIds)) {
            LambdaQueryWrapper<HisGoodsCar> lwq = new LambdaQueryWrapper<>();
            lwq.in(HisGoodsCar::getId, carIds);
            lwq.eq(HisGoodsCar::getMemberId, loginUser.getUserId());
            hisGoodsCarMapper.delete(lwq);
        }
        return order;
    }

    /**
     * 修改商城订单
     *
     * @param bo 商城订单
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HisGoodsOrderBo bo) {
        HisGoodsOrder update = MapstructUtils.convert(bo, HisGoodsOrder.class);
        HisGoodsOrderVo hisGoodsOrderVo = baseMapper.selectVoById(update.getId());
        if (StringUtils.isEmpty(hisGoodsOrderVo.getLogisticsNo())) {
            update.setStatus(OrderStatusConstant.SHOP_SHIPPED);
            update.setDeliveryTime(new Date());
        }

        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HisGoodsOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除商城订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
//---------------------------------------------------小程序--------------------------------------------------------------------------

    @Override
    public R<?> pay(String orderNo, String payType) {
        //获取用户信息
        LoginUser loginUser = LoginHelper.getLoginUser();
        HisMember member = memberMapper.selectById(loginUser.getUserId());


        //获取费
        LambdaQueryWrapper<HisGoodsOrder> orderLqw = new LambdaQueryWrapper<>();
        orderLqw.eq(HisGoodsOrder::getOrderNumber, orderNo);
        orderLqw.eq(HisGoodsOrder::getDelFlag, 0);
        HisGoodsOrderVo hisGoodsOrderVo = baseMapper.selectVoOne(orderLqw);


        OrderModel orderModel = new OrderModel();
        orderModel.setOrderNumber(hisGoodsOrderVo.getOrderNumber());
        orderModel.setRemark(loginUser.getUsername() + "商城订单");
        Double money = hisGoodsOrderVo.getTotalPrice().doubleValue();
        orderModel.setTotalFee(money);

        orderModel.setOpenId(member.getOpenId());
        orderModel.setOrderId(hisGoodsOrderVo.getOrderNumber());
        R<?> result = paymentController.pay(String.valueOf(payType), orderModel);


        return result;
    }


    @Override
    public Boolean updateOrder(R resultMag) {
        boolean flag = false;
        ReturnOrderModel returnOrderModel = (ReturnOrderModel) resultMag.getData();
        //根据订单id查询订单
        if (returnOrderModel.getResultCode() == 1) {
            LambdaQueryWrapper<HisGoodsOrder> lq = new LambdaQueryWrapper<>();
            lq.eq(HisGoodsOrder::getOrderNumber, returnOrderModel.getOrderNumber());
            lq.eq(HisGoodsOrder::getDelFlag, 0);
            HisGoodsOrder byOrderNumber = baseMapper.selectOne(lq);
            if (byOrderNumber != null) {
                //待诊断（已支付）
                byOrderNumber.setStatus(OrderStatusConstant.SHOP_PAID);
                byOrderNumber.setPayPrice(byOrderNumber.getTotalPrice());
                byOrderNumber.setPayTime(DateUtils.getNowDate());
                baseMapper.updateById(byOrderNumber);

                List<HisGoodsDetails> hisGoodsDetails = detailsMapper.selectList(new LambdaQueryWrapper<HisGoodsDetails>()
                    .eq(HisGoodsDetails::getOrderId, byOrderNumber.getId()));
                for (HisGoodsDetails details : hisGoodsDetails) {
                    HisGoods hisGoods = goodsMapper.selectById(details.getGoodsId());
                    hisGoods.setSales(hisGoods.getSales() + details.getCount());
                }
                detailsMapper.updateBatchById(hisGoodsDetails);
                //返回值
                flag = true;
            }
        }
        return flag;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> update(HisGoodsOrder goodsOrder) {
        String refundCause = "无";
        if (ObjectUtil.isNotEmpty(goodsOrder.getRefundCause())) {
            refundCause = goodsOrder.getRefundCause();
        }


//        registration.setStatus(2l);
        //获取此条数据信息
        HisGoodsOrder hisGoodsOrder = baseMapper.selectById(goodsOrder.getId());
//        LambdaQueryWrapper<HisGoodsDetails> orderLqw = new LambdaQueryWrapper<>();
//        orderLqw.eq(HisGoodsDetails::getOrderId, goodsOrder.getId());
//        List<HisGoodsDetailsVo> detailsVos = detailsMapper.selectVoList(orderLqw);
//
//        // 判断需要退款的商品列表id是否存在详情列表
//        boolean containsAll = containsDetailIds(detailsVos, goodsOrder.getDetailId());
//        if (!containsAll){
//            return R.fail("存在未购买商品");
//        }


        if (hisGoodsOrder.getTotalPrice().doubleValue() != 0.0) {
            // 退费
            HisMemberRefund hisMemberRefund = memberRefundService.getByGoodsOrderId(hisGoodsOrder.getId().toString());
            if (Objects.isNull(hisMemberRefund)) {
                Long memberId = LoginHelper.getUserId();
                HisMember hisMember = memberMapper.selectById(memberId);
                hisMemberRefund = new HisMemberRefund();
                hisMemberRefund.setStatus("1")
                    .setOrderTreatId(hisGoodsOrder.getId())
                    .setOrderType(OrderTypeConstant.ORDER_COMMODITY_TREAT)
                    .setCreateTime(new Date())
                    .setCheckStatus("0")
                    .setRefundCause(refundCause)
                    .setOperator(hisMember.getName())
                    .setMemberId(hisGoodsOrder.getMemberId())
                    .setMoney(hisGoodsOrder.getPayPrice().doubleValue());
                hisGoodsOrder.setStatus(OrderStatusConstant.SHOP_REFUNDING);
                hisGoodsOrder.setRefundCause(refundCause);
                memberRefundService.save(hisMemberRefund);
            } else {
                hisMemberRefund.setRefundCause(refundCause)
                    .setCheckStatus("0")
                    .setUpdateTime(new Date());
                memberRefundService.updateById(hisMemberRefund);
            }
            if (!"2".equals(hisMemberRefund.getStatus()) && "1".equals(hisMemberRefund.getCheckStatus())) {
                WxRefundResponseDTO dto = wxHandleUtil.refundResponseDTO(hisMemberRefund.getId());
                if (dto.isSuccess()) {
                    hisGoodsOrder.setStatus(OrderStatusConstant.SHOP_CANCEL);
                    hisMemberRefund.setStatus("2");
                    memberRefundService.updateById(hisMemberRefund);
                } else {
                    return R.error(500, "取消订单失败： " + dto.getMessage());
                }
            }
        } else {
            // 直接取消(未支付、带接诊且免费)
            hisGoodsOrder.setStatus(OrderStatusConstant.SHOP_CANCEL);
        }
        if (baseMapper.updateById(hisGoodsOrder) > 0) {
            return R.ok();
        } else {
            return R.errorCode(CommonCode.UPDATE_FAIL);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> ref(HisGoodsOrder goodsOrder) {
        HisGoodsOrder order = baseMapper.selectById(goodsOrder.getId());
        if (!order.getMemberId().equals(LoginHelper.getUserId())) {
            return R.fail("订单与用户不匹配");
        }
        order.setStatus(OrderStatusConstant.SHOP_PAID);

        HisMemberRefund byGoodsOrderId = memberRefundService.getByGoodsOrderId(order.getId().toString());
        if (ObjectUtil.isEmpty(byGoodsOrderId)) {
            return R.fail("未申请退款");
        }

        baseMapper.updateById(order);

        memberRefundService.removeById(byGoodsOrderId);
        return R.ok();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<?> confirm(HisGoodsOrder goodsOrder) {
        HisGoodsOrder order = baseMapper.selectById(goodsOrder.getId());
        if (!order.getMemberId().equals(LoginHelper.getUserId())) {
            return R.fail("订单与用户不匹配");
        }
        order.setStatus(OrderStatusConstant.SHOP_EVALUATE);
        baseMapper.updateById(order);
        return R.ok();
    }

    private LambdaQueryWrapper<HisGoodsOrder> xcxBuildQueryWrapper(HisGoodsOrderBo bo) {
        Long userId = LoginHelper.getUserId();

        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HisGoodsOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(HisGoodsOrder::getMemberId, userId);
        lqw.eq(StringUtils.isNotBlank(bo.getLogisticsNo()), HisGoodsOrder::getLogisticsNo, bo.getLogisticsNo());
        lqw.eq(bo.getLogisticsCompanyId() != null, HisGoodsOrder::getLogisticsCompanyId, bo.getLogisticsCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNumber()), HisGoodsOrder::getOrderNumber, bo.getOrderNumber());

        if (ObjectUtil.isNotEmpty(bo.getStatus())) {
            if (bo.getStatus().contains(",")) {
                // 如果 status 包含逗号，拆分成多个值并使用 in 条件
                String[] statusArray = bo.getStatus().split(",");
                lqw.in(HisGoodsOrder::getStatus, Arrays.asList(statusArray));
            } else {
                // 如果 status 不包含逗号，直接使用 eq 条件
                lqw.eq(HisGoodsOrder::getStatus, bo.getStatus());
            }
        }

        lqw.eq(HisGoodsOrder::getDelFlag, 0);
        lqw.orderByDesc(HisGoodsOrder::getCreateTime);
        return lqw;
    }

    /**
     * 校验并批量删除商城订单信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean xcxDeleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            LambdaQueryWrapper<HisGoodsOrder> lqw = new LambdaQueryWrapper<>();

            lqw.in(HisGoodsOrder::getId, ids);
            List<HisGoodsOrder> hisGoodsOrders = baseMapper.selectList(lqw);
            hisGoodsOrders.forEach(r -> {
                if (!r.getMemberId().equals(LoginHelper.getUserId())) {
                    throw new ServiceException("操作失败，当前登录用户与订单用户不匹配");
                }
            });
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 分页查询商城订单列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 商城订单分页列表
     */
    @Override
    public TableDataInfo<HisGoodsOrderVo> xcxQueryPageList(HisGoodsOrderBo bo, PageQuery pageQuery) {
        // 构建查询条件包装器，使用传入的业务对象 bo
        LambdaQueryWrapper<HisGoodsOrder> lqw = xcxBuildQueryWrapper(bo);

        // 根据查询条件包装器和分页参数，从数据库中查询 HisGoodsOrder 的分页结果，并转换为 HisGoodsOrderVo 对象
        Page<HisGoodsOrderVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 遍历查询结果中的每一条记录
        result.getRecords().forEach(obj -> {
            // 根据当前订单的 ID 查询对应的 HisGoodsDetails 记录列表
            List<HisGoodsDetailsVo> hisGoodsDetails = detailsMapper.selectVoList(
                Wrappers.lambdaQuery(HisGoodsDetails.class)
                    .eq(HisGoodsDetails::getOrderId, obj.getId())
            );

            // 遍历 HisGoodsDetails 记录列表
            hisGoodsDetails.forEach(item -> {
                // 根据商品 ID 查询对应的商品信息，并设置到 HisGoodsDetailsVo 对象中
                HisGoodsVo hisGoodsVo = goodsMapper.selectVoById(item.getGoodsId());
                item.setGoods(BeanUtil.copyProperties(hisGoodsVo, HisExcelGoodsVo.class));
            });

            // 将查询到的 HisGoodsDetails 记录列表设置到当前订单对象中
            obj.setGoodsOrderDetails(hisGoodsDetails);
        });

        // 构建并返回包含分页结果的 TableDataInfo 对象
        return TableDataInfo.build(result);

    }


    /**
     * 查询符合条件的商城订单列表
     *
     * @param id 查询条件
     * @return 商城订单列表
     */
    @Override
    public HisGoodsOrderVo xcxQueryById(Long id) {
        HisGoodsOrderVo hisGoodsOrderVo = baseMapper.selectVoById(id);

        // 遍历查询结果中的每一条记录

        // 根据当前订单的 ID 查询对应的 HisGoodsDetails 记录列表
        List<HisGoodsDetailsVo> hisGoodsDetails = detailsMapper.selectVoList(
            Wrappers.lambdaQuery(HisGoodsDetails.class)
                .eq(HisGoodsDetails::getOrderId, hisGoodsOrderVo.getId())
        );

        // 遍历 HisGoodsDetails 记录列表
        hisGoodsDetails.forEach(item -> {
            // 根据商品 ID 查询对应的商品信息，并设置到 HisGoodsDetailsVo 对象中
            HisGoodsVo hisGoodsVo = goodsMapper.selectVoById(item.getGoodsId());
            item.setGoods(BeanUtil.copyProperties(hisGoodsVo, HisExcelGoodsVo.class));
        });

        // 将查询到的 HisGoodsDetails 记录列表设置到当前订单对象中
        hisGoodsOrderVo.setGoodsOrderDetails(hisGoodsDetails);

        hisGoodsOrderVo.setAddress(memberAddressService.getById(hisGoodsOrderVo.getAddressId()));


        return hisGoodsOrderVo;
    }


    // 假设 detailIds 是传递进来的 detailId 列表
    public boolean containsDetailIds(List<HisGoodsDetailsVo> detailsVos, List<Long> detailIds) {
        for (Long detailId : detailIds) {
            boolean found = false;
            for (HisGoodsDetailsVo detailsVo : detailsVos) {
                if (detailsVo.getId().equals(detailId)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                return false;
            }
        }
        return true;
    }
}
